package _2022.hot100._239_滑动窗口最大值;

import java.util.*;

/**
 * @author： YHSimon
 * @date： 2022-05-20 09:10
 */
public class Solution {

    // 单调队列 双端队列实现 34ms
    public int[] maxSildingWindow(int[] nums, int k) {
        int n = nums.length;
        Deque<Integer> deque = new LinkedList<>();
        for (int i = 0; i < k; i++) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
        }

        int[] ans = new int[n - k + 1];
        ans[0] = nums[deque.peekFirst()];
        for (int i = k; i < n; i++) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
            while (deque.peekFirst() <= i - k) {
                deque.pollFirst();
            }
            ans[i - k + 1] = nums[deque.peekFirst()];
        }
        return ans;
    }

    // 暴力求解 2098ms
    public int[] maxSlidingWindow(int[] nums, int k) {
        int[] ans = new int[nums.length - k + 1];
        int count = 0;
        int max = Integer.MIN_VALUE;
        // 初始化
        for (int i = 0; i < k; i++) {
            max = Math.max(max, nums[i]);
        }
        ans[count++] = max;
        int left = 1, right = k;
        while (right < nums.length) {
            if (nums[left - 1] != max && nums[right] <= max) {
                ans[count++] = max;
            } else if (nums[left - 1] != max && nums[right] > max) {
                ans[count++] = nums[right];
                max = nums[right];
            } else {
                max = nums[left];
                for (int i = left; i <= right; i++) {
                    max = Math.max(max, nums[i]);
                }
                ans[count++] = max;
            }
            left++;
            right++;
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        // System.out.println(Arrays.toString(s.maxSlidingWindow(new int[]{1,3,-1,-3,5,3,6,7}, 3)));
        // System.out.println(Arrays.toString(s.maxSlidingWindow(new int[]{1}, 1)));
        System.out.println(Arrays.toString(s.maxSlidingWindow(new int[]{2, 4, 7}, 2)));
    }
}
